package com.lucifer.cloud.auth.support;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.lucifer.cloud.auth.property.CustomSmsAliProperties;
import darabonba.core.client.ClientOverrideConfiguration;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;


import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @author lucifer
 * @date 2023/11/1 10:57
 */
@Slf4j
@Component
public class AliSendSmsOperator implements SmsOperator{
    @Resource
    private CustomSmsAliProperties customSmsProperties;

    public SmsResponse sendSms(String phoneNumbers,String code) {
        JSONObject obj = JSONUtil.createObj();
        obj.set("code",code);
        String templateParam = JSONUtil.toJsonStr(obj);

        // Configure Credentials authentication information, including ak, secret, token
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set.
                .accessKeyId(customSmsProperties.getAccessKeyId())
                .accessKeySecret(customSmsProperties.getAccessKeySecret())
                //.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // use STS token
                .build());

        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou") // Region ID
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();

        // Parameter settings for API request
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .phoneNumbers(phoneNumbers)
                .signName(customSmsProperties.getSignName())
                .templateCode(customSmsProperties.getTemplateCode())
                //.templateParam("{\"code\":\"1234\"}")
                .templateParam(templateParam)
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();

        // Asynchronously get the return value of the API request
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        // Synchronously get the return value of the API request
        SendSmsResponse resp = null;
        try {
            resp = response.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        // Asynchronous processing of return values
//        response.thenAccept(resp1 -> {
//            System.out.println(new Gson().toJson(resp1));
//        }).exceptionally(throwable -> { // Handling exceptions
//            System.out.println(throwable.getMessage());
//            return null;
//        });

        // Finally, close the client
        //client.close();
        SmsResponse smsResponse = new SmsResponse();
        if(Objects.nonNull(resp.getBody())){
            smsResponse.setRequestId(resp.getBody().getRequestId());
            smsResponse.setCode(resp.getBody().getCode());
            smsResponse.setMessage(resp.getBody().getMessage());
            smsResponse.setBizId(resp.getBody().getBizId());
        }
        return smsResponse;
    }


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //sendSms("15693323897", "1234");
    }
}
